﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using System.Web;

namespace OAuthServer.Controllers;

public class LoginController : Controller
{
    [HttpGet]
    public IActionResult Index(string returnUrl)
    {
        ViewBag.ReturnUrl = HttpUtility.UrlEncode(returnUrl);
        return View();
    }
    [HttpPost]
    public async Task<IActionResult> Index(string returnUrl, string type)
    {
        returnUrl = returnUrl ?? Url.Content("~/"); // 默认返回主页
        //cookie
        await HttpContext.SignInAsync("cookie", new ClaimsPrincipal(
            new ClaimsIdentity(
                new Claim[]
                {
                    new Claim(ClaimTypes.Name,"admin"),
                    new Claim(ClaimTypes.NameIdentifier,Guid.NewGuid().ToString())
                }, "cookie"
                )
            ));

        // 如果有returnUrl并且是绝对URL，则重定向回该地址
        if (Url.IsLocalUrl(returnUrl))
        {
            return Redirect(returnUrl);
        }
        else
        {
            return this.RedirectToAction(nameof(HomeController.Index), "Home");
        }
    }

    [HttpGet]
    public async Task<IActionResult> Logout()
    {
        //AuthenticationProperties properties = new AuthenticationProperties()
        //{
        //    ExpiresUtc = DateTime.Now.AddDays(-100)
        //};
        await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
        return RedirectToAction("Login");
    }
}
